package com.gitee.xqxyxchy.crypto.impl;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;

import com.gitee.xqxyxchy.crypto.CryptoParam;
import com.gitee.xqxyxchy.crypto.ICryptoService;
import com.gitee.xqxyxchy.crypto.ParamKey;

public class Sm3Crypto implements ICryptoService {

	private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
	private static final String DEFAULT_HEX_KEY = "5bc0c302700c35b4";

	@Override
	public String encrypt(String originData, CryptoParam... params) {
		try {
			String hexKey = CryptoParam.Builder.create().get(ParamKey.HEX_KEY.getKey(), DEFAULT_HEX_KEY, params);
			// 将字符串转换成byte数组
			byte[] srcData = originData.getBytes(DEFAULT_CHARSET);
			// 密钥
			byte[] key = Hex.decode(hexKey);
			// 计算hash
			KeyParameter keyParameter = new KeyParameter(key);
			SM3Digest digest = new SM3Digest();
			HMac mac = new HMac(digest);
			mac.init(keyParameter);
			mac.update(srcData, 0, srcData.length);
			byte[] result = new byte[mac.getMacSize()];
			mac.doFinal(result, 0);
			// 将返回的hash值转换成16进制字符串
			return Hex.toHexString(result);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String decrypt(String encryptedData, CryptoParam... params) {
		throw new RuntimeException("Not supported.");
	}

}
